// pages/detail/detail.js
import Dialog from '@vant/weapp/dialog/dialog';
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIphoneX: app.globalData.isIphoneX,
    goodsId: "", // 商品id
    detail: {}, // 商品信息
    selectFlag: 0, // 商品类别选择
    drawFlag: false, // 领取优惠券标识
    risk: '', // 风险提示
    show: false, // 购买弹框
    show1: false, // 分享弹框
    shareImg: '', // 分享图片
    show2: false, // 保存图片
    show2: false, // 放大图片
    timeList: ['00', '00', '00', '00'] // 预售倒计时
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('==== options ====', options)
    // options.id = 1009009
    if (options.scene) {
      console.info('==== scene ====',decodeURIComponent(options.scene))
      options.id = decodeURIComponent(options.scene).split('&')[0]
      options.userId = decodeURIComponent(options.scene).split('&')[1]
      options.grouponNo = decodeURIComponent(options.scene).split('&')[2]
      options.drawFlag = decodeURIComponent(options.scene).split('&')[3] == 'v1' ? true : ''
      console.log('==== options ====', options)
    }
    this.setData({
      goodsId: options.id,
      userId: options.userId,
      grouponNo: options.grouponNo,
      drawFlag: options.drawFlag
    })
    this.getRisk()
  },

  //  获取风险提示文案
  getRisk() {
    wx.get('/api/config/configKey?key=risk_warning', res => {
      if (res.code == 200) {
        this.setData({
          risk: res.msg.replace(/\\n/g, "\n")
        })
      }
    }, fail => {})
  },

  // 选择回报选择
  tabClick(e) {
    console.log(e)
    this.setData({
      selectFlag: e.currentTarget.dataset['index']
    })
  },
  
  // 跳转确认订单
  toOrderConfirm() {
    if (this.data.detail.goodsProd[this.data.selectFlag].number<=0) {
      return
    }
    let that = this
    wx.setStorage({
      key:"shopDetail",
      data: {
        selectFlag: this.data.selectFlag,
        userId: this.data.userId,
        grouponNo: this.data.grouponNo,
        ...this.data.detail
      },
      success() {
        that.setData({
          show: false
        })
        let url = '/pages/orderConfirm/orderConfirm'
        if (that.data.drawFlag) {
          url += '?drawFlag=true'
        }
        wx.navigateTo({
          url
        })
      }
    })
  },

  // 跳转协议
  jumpAgree(e) {
    let url
    if (e.currentTarget.dataset.type == 1) {
      url = encodeURIComponent(app.globalData.host+'/doc/refund.html')
      wx.navigateTo({
        url: `/pages/webview/webview?url= ${url}`,
      })
    } else {
      
    }
  },

  // 跳转问卷
  toWenQuan() {
    wx.navigateTo({
      url: '/pages/wenjuan/wenjuan',
    })
  },

  // 分享
  share(e) {
    let api = '/api/goods/'
    if (e.currentTarget.dataset.type == 'link') {
      api += `shareUrl?goodsId=${this.data.goodsId}`
    } else if (e.currentTarget.dataset.type == 'link_wb') {
      api += `shareUrl?goodsId=${this.data.goodsId}&urlType=1`
    } else {
      api += `shareImage?goodsId=${this.data.goodsId}`
    }
    wx.get(api, res => {
      console.log(e.currentTarget.dataset.type, res)
      if (res.code == 200) {
        if (e.currentTarget.dataset.type == 'link' || e.currentTarget.dataset.type == 'link_wb') {
          wx.setClipboardData({
            data: res.data.shareUrl,
            success (_res) {
              wx.getClipboardData({
                success (__res) {
                  console.log(__res.data) // data
                }
              })
            }
          })
        } else {
          wx.showLoading({
            mask: true
          })
          this.setData({
            shareImg: res.data.shareImg,
            show2: true,
            show1: false
          })
        }
      }
    }, fail => {})
  },

  imageLoad() {
    console.info('==== 图片加载完成 ====')
    wx.hideLoading()
  },

  // 保存图片
  save() {
    let that = this
    wx.showLoading({
      mask: true
    })
    wx.getImageInfo({
      src:  that.data.shareImg,
      success (ress) {
        console.log(ress)
        wx.saveImageToPhotosAlbum({
          filePath: ress.path,
          success(res) {
            console.log(res)
            wx.hideLoading()
            that.setData({
              show2: false
            })
            wx.showToast({
              title: '图片保存成功',
              icon: 'none',
              duration: 2000
            })
          }
        })
      }
    })
    
  },

  lookGood() {
    wx.post(`${wx.api.goodAdd}${this.data.goodsId}`, {}, res=> {
      console.log('==== lookGood ====', res)
      if (res.code == 200) {
        this.getDetail()
        Dialog.alert({
          title: '看好成功',
          message: '实时获取最新项目进度',
          confirmButtonText: '好的'
        })
      }
    })
  },
  
  lookNoGood() {
    Dialog.confirm({
      title: '确认取消看好？',
      message: '取消后将收不到众筹开始提示',
      confirmButtonText: '取消看好',
      cancelButtonText: '不取消'
    }).then(() => {
      wx.get(`${wx.api.goodRemove}${this.data.goodsId}`, res=> {
        console.log('==== lookNoGood ====', res)
        if (res.code == 200) {
          this.getDetail()
          Dialog.alert({
            title: '温馨提示',
            message: '已取消',
            confirmButtonText: '好的'
          })
        }
      })
    })
  },
  
  // 跳转商城详情
  toShopDetail() {
    wx.navigateTo({
      url: `/pages/shopDetail/shopDetail?id=${this.data.detail.mallGoodsId}&fromPage=detial`
    })
  },

  showPopup() {
    this.setData({ show: true });
  },

  onClose() {
    this.setData({ show: false });
  },

  showPopup1() {
    this.setData({ show1: true });
  },

  onClose1() {
    this.setData({ show1: false });
  },

  showPopup2() {
    this.setData({ show2: true });
  },

  showPopup3() {
    this.setData({ show3: true });
  },

  onClose2() {
    this.setData({ show2: false });
  },

  onClose3() {
    this.setData({ show3: false });
  },
  
  // 返回页面顶部
  scrollTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getDetail()
  },

  getDetail() {
    wx.get("/api/goods/detail?goodsId="+ this.data.goodsId, res => {
      console.log('==== detail ===', res)
      // 处理商品已购买价格
      res.data.totalAmount = Math.floor((res.data.totalAmount*100 + res.data.dummyMoney*100))/100
      // 处理商品图片富文本
      res.data.detail = res.data.detail.replace(/\/\>/gi, ' style="display:block" width="100%" height=""/>')
      // 处理商品类型 数组转成字符串
      res.data.goodsProd = res.data.goodsProd.map(item=> {
        return {...item, specificationsText: item.specifications.join('+')}
      })
      // 处理剩余天数 
      let nowTime = new Date()*1
      let endTime = new Date(res.data.endTime.replace(/-/g, '/'))*1
      let endDay = Math.floor((endTime - nowTime) / (1000*3600*24))
      res.data.endDay =  endDay > 0 ? endDay : 0
      this.setData({
        detail: res.data
      })
      if (res.data.status == 0) { // 预售 倒计时
        this.singleCountDown()
      }
    }, fail => {})
  },

  // 倒计时定时器
  singleCountDown() {
    let endTime = new Date(this.data.detail.startTime.replace(/-/g, "/")).getTime()
    var currentTime = new Date().getTime(); //当前时间时间戳
    var time = (endTime - currentTime);
    // // 商品已过购买期限
    if (time > 0) {
      let d,h,m,s;
      d = Math.floor(time/1000/60/60/24);
      h = Math.floor(time/1000/60/60%24);
      m = Math.floor(time/1000/60%60);
      s = Math.floor(time/1000%60);
      var timeIntervalSingle = setTimeout(this.singleCountDown, 1000);
      this.setData({
        timeList: [this.timeFormat(d), this.timeFormat(h), this.timeFormat(m), this.timeFormat(s)],
        timeIntervalSingle
      })
    } else {
      this.setData({
        timeList: ['00', '00', '00', '00']
      })
      this.data.timeIntervalSingle ? clearTimeout(this.data.timeIntervalSingle) : ''; //清除定时器
      this.getDetail()
    }
  },

  //时间显示小于10的前面补0方法
  timeFormat(param) {
    return param < 10 ? '0' + param : param;
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title:  this.data.detail.name,
      path: `/pages/detail/detail?id=${this.data.goodsId}`,
      imageUrl: this.data.detail.picUrl
    }
  },

   /**
   * 用户点击右上角分享转发到朋友圈
   */
  onShareTimeline() {
    return {
      title:  this.data.detail.name,
      query: `id=${this.data.goodsId}`,
      imageUrl: this.data.detail.picUrl
    }
  }
})